package com.chengyu.core.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.chengyu.core.constants.*;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.MemberTypes;
import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.CommonException;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.model.UmsMember;
import com.chengyu.core.model.UserToken;
import com.chengyu.core.request.*;
import com.chengyu.core.response.FrontLoginConfigResponse;
import com.chengyu.core.response.LoginResponse;
import com.chengyu.core.service.LoginService;

import com.chengyu.core.service.SystemConfigService;
import com.chengyu.core.service.UserTokenService;
import com.chengyu.core.service.WechatService;
import com.chengyu.core.service.member.MemberService;

import com.chengyu.core.util.RedisUtil;
import com.chengyu.core.utils.CommonDateUtil;
import com.chengyu.core.utils.CommonUtil;
import com.chengyu.core.utils.WxUtil;

import com.chengyu.core.FrontTokenComponent;

import com.chengyu.core.vo.WeChatAuthorizeLoginUserInfoVo;
import com.chengyu.core.vo.WeChatMiniAuthorizeVo;
import com.chengyu.core.vo.WeChatOauthToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 移动端登录服务类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);


    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Autowired
    private FrontTokenComponent tokenComponent;

    @Autowired
    private MemberService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private WechatService wechatService;


    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private SystemConfigService systemConfigService;


    @Autowired
    private PasswordEncoder passwordEncoder;

//    /**
//     * 发送短信验证码
//     * @param phone 手机号
//     * @return Boolean
//     */
//    @Override
//    public Boolean sendLoginCode(String phone) {
//        return smsService.sendCommonCode(phone);
//    }

    /**
     * 检测手机验证码
     *
     * @param phone 手机号
     * @param code  验证码
     */
    private void checkValidateCode(String phone, String code) {
        Object validateCode = redisUtil.get(SmsConstants.SMS_VALIDATE_PHONE + phone);
        if (ObjectUtil.isNull(validateCode)) {
            throw new CommonException("验证码已过期");
        }
        if (!validateCode.toString().equals(code)) {
            throw new CommonException("验证码错误");
        }
        //删除验证码
        redisUtil.delete(SmsConstants.SMS_VALIDATE_PHONE + phone);
    }


//
//    /**
//     * 手机号验证码登录
//     * @param loginRequest 登录信息
//     * @return LoginResponse
//     */
//    @Override
//    public LoginResponse phoneCaptchaLogin(LoginMobileRequest loginRequest) {
//        if (StrUtil.isBlank(loginRequest.getCaptcha())) {
//            throw new CommonException("手机号码验证码不能为空");
//        }
//        Integer spreadPid = Optional.ofNullable(loginRequest.getSpreadPid()).orElse(0);
//        //检测验证码
//        checkValidateCode(loginRequest.getPhone(), loginRequest.getCaptcha());
//        //查询用户信息
//        UmsMember user = userService.getByPhone(loginRequest.getPhone());
//        if (ObjectUtil.isNull(user)) {// 此用户不存在，走新用户注册流程
//            user = userService.registerPhone(loginRequest.getPhone(), spreadPid);
//            return getLoginResponse_V1_3(user, true);
//        }
//        return commonLogin(user, spreadPid);
//
//    }

//    /**
//     * 手机号密码登录
//     * @param loginRequest 登录信息
//     * @return LoginResponse
//     */
//    @Override
//    public LoginResponse phonePasswordLogin(LoginPasswordRequest loginRequest) {
//        if (StrUtil.isBlank(loginRequest.getPassword())) {
//            throw new CommonException("密码不能为空");
//        }
//
//        //查询用户信息
//        UmsMember user = userService.getByPhone(loginRequest.getPhone());
//        if (ObjectUtil.isNull(user)) {// 此用户不存在，走新用户注册流程
//            throw new CommonException("用户名或密码不正确");
//        }
//        if (!CommonUtil.encryptPassword(loginRequest.getPassword(), loginRequest.getPhone()).equals(user.getPwd())) {
//            throw new CommonException("用户名或密码不正确");
//        }
//        if (!user.getStatus()) {
//            throw new CommonException("当前帐户已禁用，请与管理员联系！");
//        }
//        Integer spreadPid = Optional.ofNullable(loginRequest.getSpreadPid()).orElse(0);
//        return commonLogin(user, spreadPid);
//    }

    /**
     * 微信公众号授权登录
     * @param request 登录参数
     * @return LoginResponse
     */
    @Override
    public LoginResponse wechatPublicLogin(WechatPublicLoginRequest request) throws ServiceException {
        // 通过code获取获取公众号授权信息
        WeChatOauthToken oauthToken = wechatService.getOauth2AccessToken(request.getCode());

        logger.info("wechatPublicLogin oauthToken = {}", oauthToken);
        //检测是否存在
        UserToken userToken = userTokenService.getByOpenidAndType(oauthToken.getOpenId(),  UserConstants.USER_TOKEN_TYPE_WECHAT);

        logger.info("wechatPublicLogin userToken = {}", userToken);
        if (ObjectUtil.isNotNull(userToken)) {// 已存在，正常登录
            UmsMember user = userService.getById(userToken.getUid());
            if (ObjectUtil.isNull(user) && user.getStatus()!=1) {
                throw new CommonException("当前账户异常，请联系管理员！");
            }
            // 记录最后一次登录时间
            user.setLastLoginTime(CommonDateUtil.nowDateTime());
            Boolean execute = transactionTemplate.execute(e -> {
                try {

                    UmsMember updateMember = new UmsMember();
                    updateMember.setId(user.getId());
                    updateMember.setLastLoginTime(CommonDateUtil.nowDateTime());
//                    memberService.updateMember(updateMember);

                    userService.updateMember(updateMember);
                } catch (ServiceException serviceException) {
                    serviceException.printStackTrace();
                }
                return Boolean.TRUE;
            });
            if (!execute) {
                logger.error(StrUtil.format("APP微信登录记录最后一次登录时间失败，uid={}", user.getId()));
            }
            return getLoginResponseNew(user,false);
        }else {
//            // 没有用户，走创建用户流程// 从微信获取用户信息，存入Redis中，将key返回给前端，前端在下一步绑定手机号的时候下发


            WeChatAuthorizeLoginUserInfoVo userInfo = wechatService.getSnsUserInfo(oauthToken.getAccessToken(), oauthToken.getOpenId());
            logger.info("微信公众号授权登录，开放平台用户信息 = {}", JSONObject.toJSONString(userInfo));


            RegisterThirdUserRequest registerThirdUmsMemberRequest = new RegisterThirdUserRequest();
            registerThirdUmsMemberRequest.setSpreadPid(0);
            registerThirdUmsMemberRequest.setType("wechat");
            registerThirdUmsMemberRequest.setOpenId(oauthToken.getOpenId());
            String key = SecureUtil.md5(oauthToken.getOpenId());
            redisUtil.set(key, JSONObject.toJSONString(registerThirdUmsMemberRequest), (long) (60 * 2), TimeUnit.MINUTES);
            UmsMember member = new UmsMember();
            member.setType(CommonConstant.BUYER);

            member.setRegisterType(registerThirdUmsMemberRequest.getType());

            member.setPassword(CommonUtil.createPwd(com.chengyu.core.utils.StringUtils.getStringRandom(32)));
//            member.setNickname(registerThirdUmsMemberRequest.getOpenId());
            member.setNickname(userInfo.getNickName());
            member.setCode(registerThirdUmsMemberRequest.getOpenId());
//            member.setHeadImg(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
            member.setHeadImg(userInfo.getHeadimgurl());

//            member.setGender("");
            member.setGender(userInfo.getSex());
            member.setAddress("");


            member.setCity(userInfo.getCity());
            member.setProvince(userInfo.getProvince());

            member.setGzhOpenId(userInfo.getOpenId());
            member.setUnionid(userInfo.getUnionId());



            member.setLastLoginTime(CommonDateUtil.nowDateTime());

            //推荐人
            String  inviteCode  = request.getInviteCode();
            if(!inviteCode.equals("")){
                UmsMember tMember = userService.getMemberByParams(inviteCode, MemberTypes.INVITE_CODE);
                if(tMember!=null){
                    member.setTjrId(tMember.getId());
                }
            }


            UmsMember finalUmsMember = member;


            System.out.print(finalUmsMember);
            try {
                Boolean execute = transactionTemplate.execute(e -> {
                    //进行注册登录
                    String token = "";
                    try {
                        userService.register(finalUmsMember, false);
                    } catch (ServiceException serviceException) {
                        serviceException.printStackTrace();
                    }
                    return null;
                });

                System.out.print("22222222222");
                //校验code是否已被注册
                UmsMember user = userService.getMemberByParams(registerThirdUmsMemberRequest.getOpenId(), MemberTypes.CODE);
                userTokenService.bind(registerThirdUmsMemberRequest.getOpenId(), UserConstants.USER_TOKEN_TYPE_WECHAT, user.getId());
                return getLoginResponseNew(user,true);
            } catch (TransactionException e) {
                e.printStackTrace();

                System.out.print("3333333333");
//                LoginResponse loginResponse = new LoginResponse();
                return  getLoginResponseNew(null,true);
            }
        }


//
//
//        Integer spreadPid = Optional.ofNullable(request.getSpreadPid()).orElse(0);
//        LoginResponse loginResponse = new LoginResponse();
//        if (ObjectUtil.isNotNull(userToken)) {// 已存在，正常登录
//            UmsMember user = userService.getById(userToken.getUid());
//            if (user.getStatus()<1) {
//                throw new CommonException("当前账户已禁用，请联系管理员！");
//            }
//            return commonLogin(user, spreadPid);
//        }
//        // 没有用户，走创建用户流程
//        // 从微信获取用户信息，存入Redis中，将key返回给前端，前端在下一步绑定手机号的时候下发
//        WeChatAuthorizeLoginUserInfoVo userInfo = wechatService.getSnsUserInfo(oauthToken.getAccessToken(), oauthToken.getOpenId());
//        logger.info("微信公众号授权登录，开放平台用户信息 = {}", JSONObject.toJSONString(userInfo));
//        RegisterThirdUserRequest registerThirdUmsMemberRequest = new RegisterThirdUserRequest();
//        BeanUtils.copyProperties(userInfo, registerThirdUmsMemberRequest);
//        registerThirdUmsMemberRequest.setSpreadPid(spreadPid);
//        registerThirdUmsMemberRequest.setType(UserConstants.REGISTER_TYPE_WECHAT);
//        registerThirdUmsMemberRequest.setOpenId(oauthToken.getOpenId());
//        String key = SecureUtil.md5(oauthToken.getOpenId());
//        redisUtil.set(key, JSONObject.toJSONString(registerThirdUmsMemberRequest), (long) (60 * 2), TimeUnit.MINUTES);
//
//        loginResponse.setType(LoginConstants.LOGIN_STATUS_REGISTER);
//        loginResponse.setKey(key);
//        return loginResponse;


        // 没有用户，走创建用户流程
//            // 从微信获取用户信息，存入Redis中，将key返回给前端，前端在下一步绑定手机号的时候下发
//        RegisterThirdUserRequest registerThirdUmsMemberRequest = new RegisterThirdUserRequest();
//        registerThirdUmsMemberRequest.setSpreadPid(0);
//        registerThirdUmsMemberRequest.setType(request.getType());
//        registerThirdUmsMemberRequest.setOpenId(request.getOpenId());
//        String key = SecureUtil.md5(request.getOpenId());
//        redisUtil.set(key, JSONObject.toJSONString(registerThirdUmsMemberRequest), (long) (60 * 2), TimeUnit.MINUTES);
////            LoginResponse loginResponse = new LoginResponse();
////            loginResponse.setType(LoginConstants.LOGIN_STATUS_REGISTER);
////            loginResponse.setKey(key);
////            return loginResponse;
//
//
//        UmsMember member = new UmsMember();
//        member.setType(CommonConstant.BUYER);
//
//        member.setRegisterType(registerThirdUmsMemberRequest.getType());
////            member.setPhone(registerThirdUmsMemberRequest.getPhone());
////            user.setAccount(request.getPhone());
////            user.setSpreadUid(0);
////            member.setPassword(passwordEncoder.encode(regParam.getPassword()));
//        member.setPassword(CommonUtil.createPwd(com.chengyu.core.utils.StringUtils.getStringRandom(32)));
//        member.setNickname(registerThirdUmsMemberRequest.getOpenId());
//        member.setCode(registerThirdUmsMemberRequest.getOpenId());
//        member.setHeadImg(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
//        member.setGender("");
//        member.setAddress("");
//        member.setLastLoginTime(CommonDateUtil.nowDateTime());
//        UmsMember finalUmsMember = member;
//
////            LoginResponse loginResponse = new LoginResponse();
////            loginResponse.setTokenHead(tokenHead);
//
////            tokenMap.put("member", member);
//
//        System.out.print(finalUmsMember);
//        try {
//            Boolean execute = transactionTemplate.execute(e -> {
//                //进行注册登录
//                String token = "";
//                try {
//                    userService.register(finalUmsMember, false);
//
//
//
////                        token  = userService.loginByNoPassword(finalUmsMember.getCode());
////                        loginResponse.setToken(token);
//                } catch (ServiceException serviceException) {
//                    serviceException.printStackTrace();
//                }
//                //if (token == null) {return CommonResult.validateFailed("用户名或密码错误");}
//                return null;
//            });
//
//            System.out.print("22222222222");
//            //校验code是否已被注册
//            UmsMember user = userService.getMemberByParams(registerThirdUmsMemberRequest.getOpenId(), MemberTypes.CODE);
//
//
////                if (request.getType().equals(UserConstants.REGISTER_TYPE_IOS_WX)) {
//            userTokenService.bind(registerThirdUmsMemberRequest.getOpenId(), UserConstants.USER_TOKEN_TYPE_WECHAT, user.getId());
////                }
////                if (request.getType().equals(UserConstants.REGISTER_TYPE_ANDROID_WX)) {
////                    userTokenService.bind(registerThirdUmsMemberRequest.getOpenId(), UserConstants.USER_TOKEN_TYPE_ANDROID_WX, user.getId());
////                }
////                UmsMember user = userService.getMemberByParams(userToken.getUid());
//            return getLoginResponseNew(user,true);

        }

    /**
     * 微信登录小程序授权登录
     * @param request 用户参数
     * @return LoginResponse
     */
    @Override
    public LoginResponse wechatRoutineLogin(RegisterThirdUserRequest request) throws ServiceException {
        WeChatMiniAuthorizeVo response = wechatService.miniAuthCode(request.getCode());
        //检测是否存在
        UserToken userToken = userTokenService.getByOpenidAndType(response.getOpenId(), UserConstants.USER_TOKEN_TYPE_ROUTINE);
        Integer spreadPid = Optional.ofNullable(request.getSpreadPid()).orElse(0);
        LoginResponse loginResponse = new LoginResponse();
        if (ObjectUtil.isNotNull(userToken)) {// 已存在，正常登录
            UmsMember user = userService.getById(userToken.getUid());
            if (user.getStatus()<1) {
                throw new CommonException("当前账户已禁用，请联系管理员！");
            }
            return commonLogin(user, spreadPid);
        }
        request.setSpreadPid(spreadPid);
        request.setType(UserConstants.REGISTER_TYPE_ROUTINE);
        request.setOpenId(response.getOpenId());
        String key = SecureUtil.md5(response.getOpenId());
        redisUtil.set(key, JSONObject.toJSONString(request), (long) (60 * 2), TimeUnit.MINUTES);
        loginResponse.setType(LoginConstants.LOGIN_STATUS_REGISTER);
        loginResponse.setKey(key);
        return loginResponse;
    }

    /**
     * 微信注册绑定手机号
     * @param request 请求参数
     * @return 登录信息
     */
    @Override
    public LoginResponse wechatRegisterBindingPhone(WxBindingPhoneRequest request) {
        // 检验并获取手机号
        checkBindingPhone(request);

        // 进入创建用户绑定手机号流程
        String value = redisUtil.get(request.getKey());
        if (StrUtil.isBlank(value)) {
            throw new CommonException("用户缓存已过期，请清除缓存重新登录");
        }
        RegisterThirdUserRequest registerThirdUmsMemberRequest = JSONObject.parseObject(value, RegisterThirdUserRequest.class);
        if (!request.getType().equals(registerThirdUmsMemberRequest.getType())) {
            throw new CommonException("用户的类型与缓存中的类型不符");
        }

        boolean isNew = true;
//        UmsMember user = userService.getByPhone(request.getPhone());
        UmsMember user = userService.getByPhone(request.getPhone());
        // 查询是否用对应得token
        Integer userTokenType = getUserTokenType(request.getType());
        if (ObjectUtil.isNotNull(user)) {// 历史用户校验
            if (request.getType().equals(UserConstants.REGISTER_TYPE_WECHAT) && user.getIsWechatPublic()) {
                throw new CommonException("该手机号已绑定微信公众号");
            }
            if (request.getType().equals(UserConstants.REGISTER_TYPE_ROUTINE) && user.getIsWechatRoutine()) {
                throw new CommonException("该手机号已绑定微信小程序");
            }
            if (request.getType().equals(UserConstants.REGISTER_TYPE_ANDROID_WX) && user.getIsWechatAndroid()) {
                throw new CommonException("该手机号已绑定微信Android");
            }
            if (request.getType().equals(UserConstants.REGISTER_TYPE_IOS_WX) && user.getIsWechatIos()) {
                throw new CommonException("该手机号已绑定微信IOS");
            }
            UserToken userToken = userTokenService.getTokenByUserId(user.getId(), userTokenType);
            if (ObjectUtil.isNotNull(userToken)) {
                throw new CommonException("该手机号已被注册");
            }
            isNew = false;
        } else {
            user = new UmsMember();
            user.setRegisterType(registerThirdUmsMemberRequest.getType());
            user.setPhone(request.getPhone());
//            user.setAccount(request.getPhone());
//            user.setSpreadUid(0);
            user.setPassword(CommonUtil.createPwd(request.getPhone()));
            user.setNickname(CommonUtil.createNickName(request.getPhone()));
            user.setHeadImg(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
            user.setGender("");
            user.setAddress("");
//            user.setLevel(1);
        }
        switch (request.getType()) {
            case UserConstants.REGISTER_TYPE_WECHAT:
                user.setIsWechatPublic(true);
                break;
            case UserConstants.REGISTER_TYPE_ROUTINE:
                user.setIsWechatRoutine(true);
                break;
            case UserConstants.REGISTER_TYPE_IOS_WX:
                user.setIsWechatIos(true);
                break;
            case UserConstants.REGISTER_TYPE_ANDROID_WX:
                user.setIsWechatAndroid(true);
                break;
        }
        user.setLastLoginTime(CommonDateUtil.nowDateTime());
        UmsMember finalUmsMember = user;
        boolean finalIsNew = isNew;
        Boolean execute = transactionTemplate.execute(e -> {
            Integer spreadPid = Optional.ofNullable(registerThirdUmsMemberRequest.getSpreadPid()).orElse(0);
            if (finalIsNew) {// 新用户
                // 分销绑定
                if (spreadPid > 0 && userService.checkBingSpread(finalUmsMember, registerThirdUmsMemberRequest.getSpreadPid(), "new")) {
                    finalUmsMember.setTjrUid(registerThirdUmsMemberRequest.getSpreadPid());
//                    finalUmsMember.setSpreadTime(CommonDateUtil.nowDateTime());
//                    userService.updateSpreadCountByUid(registerThirdUmsMemberRequest.getSpreadPid(), Constants.OPERATION_TYPE_ADD);
                }

                try {
                    userService.register(finalUmsMember, false);
                } catch (ServiceException serviceException) {
                    serviceException.printStackTrace();
                }

            } else {
                try {
                    userService.updateMember(finalUmsMember);
                } catch (ServiceException serviceException) {
                    serviceException.printStackTrace();
                }
                if (finalUmsMember.getTjrUid().equals(0) && spreadPid > 0) {
                    // 绑定推广关系
                    bindSpread(finalUmsMember, spreadPid);
                }
            }
            userTokenService.bind(registerThirdUmsMemberRequest.getOpenId(), userTokenType, finalUmsMember.getId());
            return Boolean.TRUE;
        });
        if (!execute) {
            logger.error(StrUtil.format("微信用户注册生成失败，openid = {}, key = {}", registerThirdUmsMemberRequest.getOpenId(), request.getKey()));
            throw new CommonException(StrUtil.format("微信用户注册生成失败，openid = {}, key = {}", registerThirdUmsMemberRequest.getOpenId(), request.getKey()));
        }
        return getLoginResponse_V1_3(finalUmsMember, isNew);
    }

    /**
     * 获取用户Token类型
     * @param type 用户注册类型
     */
    private Integer getUserTokenType(String type) {
        Integer userTokenType = 0;
        switch (type) {
            case UserConstants.REGISTER_TYPE_WECHAT:
                userTokenType = UserConstants.USER_TOKEN_TYPE_WECHAT;
                break;
            case UserConstants.REGISTER_TYPE_ROUTINE:
                userTokenType = UserConstants.USER_TOKEN_TYPE_ROUTINE;
                break;
            case UserConstants.REGISTER_TYPE_IOS_WX:
                userTokenType = UserConstants.USER_TOKEN_TYPE_IOS_WX;
                break;
            case UserConstants.REGISTER_TYPE_ANDROID_WX:
                userTokenType = UserConstants.USER_TOKEN_TYPE_ANDROID_WX;
                break;
        }
        return userTokenType;
    }

    /**
     * 绑定手机号数据校验
     */
    private void checkBindingPhone(WxBindingPhoneRequest request) {
        if (request.getType().equals(UserConstants.REGISTER_TYPE_WECHAT) || request.getType().equals(UserConstants.REGISTER_TYPE_IOS_WX) || request.getType().equals(UserConstants.REGISTER_TYPE_ANDROID_WX)) {
            if (StrUtil.isBlank(request.getPhone()) || StrUtil.isBlank(request.getCaptcha())) {
                throw new CommonException("手机号、验证码不能为空");
            }
            checkValidateCode(request.getPhone(), request.getCaptcha());
        } else {
            // 参数校验
            if (StrUtil.isBlank(request.getCode())) {
                throw new CommonException("小程序获取手机号code不能为空");
            }
            if (StrUtil.isBlank(request.getEncryptedData())) {
//                throw new CommonException("小程序获取手机号加密数据不能为空");
                throw new CommonException("请认证微信账号：获取手机号码失败");
            }
            if (StrUtil.isBlank(request.getIv())) {
                throw new CommonException("小程序获取手机号加密算法的初始向量不能为空");
            }
            // 获取appid     /** 小程序appId key */
            String programAppId = systemConfigService.getValueByKey(WeChatConstants.WECHAT_MINI_APPID);
//            String programAppId = "111";
            if (StringUtils.isBlank(programAppId)) {
                throw new CommonException("微信小程序appId未设置");
            }

            WeChatMiniAuthorizeVo response = wechatService.miniAuthCode(request.getCode());
            System.out.println("小程序登陆成功 = " + JSON.toJSONString(response));
            String decrypt = WxUtil.decrypt(programAppId, request.getEncryptedData(), response.getSessionKey(), request.getIv());
            if (StrUtil.isBlank(decrypt)) {
                throw new CommonException("微信小程序获取手机号解密失败");
            }
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            if (StrUtil.isBlank(jsonObject.getString("phoneNumber"))) {
                throw new CommonException("微信小程序没有获取到有效的手机号");
            }
            request.setPhone(jsonObject.getString("phoneNumber"));
        }
    }

    /**
     * 绑定分销关系
     *
     * @param user      UmsMember 用户user类
     * @param spreadUid Integer 推广人id
     * @return Boolean
     */
    private Boolean bindSpread(UmsMember user, Integer spreadUid) {
        Boolean checkBingSpread = userService.checkBingSpread(user, spreadUid, "old");
        if (!checkBingSpread) return false;

        user.setTjrUid(spreadUid);
//        user.setSpreadTime(CommonDateUtil.nowDateTime());

        Boolean execute = transactionTemplate.execute(e -> {
            try {
                userService.updateMember(user);
            } catch (ServiceException serviceException) {
                serviceException.printStackTrace();
            }
//            userService.updateSpreadCountByUid(spreadUid, Constants.OPERATION_TYPE_ADD);
            return Boolean.TRUE;
        });
        if (!execute) {
            logger.error(StrUtil.format("绑定推广人时出错，userUid = {}, spreadUid = {}", user.getId(), spreadUid));
        }
        return execute;
    }

    /**
     * 获取登录配置
     */
    @Override
    public FrontLoginConfigResponse getLoginConfig() {
        FrontLoginConfigResponse response = new FrontLoginConfigResponse();
        response.setLogo(systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_MOBILE_LOGIN_LOGO));
        response.setLogo("");
        return response;
    }

    /**
     * 微信登录App授权登录
     */
    @Override
    public LoginResponse wechatAppLogin(RegisterAppWxRequest request) throws ServiceException {
        //检测是否存在
        UserToken userToken = null;
        System.out.print("0000000000");

//        REGISTER_TYPE_WECHAT
        userToken = userTokenService.getByOpenidAndType(request.getOpenId(),  UserConstants.USER_TOKEN_TYPE_WECHAT);
//        if (request.getType().equals(UserConstants.REGISTER_TYPE_IOS_WX)) {
//            userToken = userTokenService.getByOpenidAndType(request.getOpenId(),  UserConstants.USER_TOKEN_TYPE_IOS_WX);
//        }
//        if (request.getType().equals(UserConstants.REGISTER_TYPE_ANDROID_WX)) {
//            userToken = userTokenService.getByOpenidAndType(request.getOpenId(),  UserConstants.USER_TOKEN_TYPE_ANDROID_WX);
//        }
//        logger.error(StrUtil.format("userToken", userToken));
        if (ObjectUtil.isNotNull(userToken)) {// 已存在，正常登录
            UmsMember user = userService.getById(userToken.getUid());
            if (ObjectUtil.isNull(user) && user.getStatus()!=1) {
                throw new CommonException("当前账户异常，请联系管理员！");
            }
//            if (!user.getStatus()) {
//                throw new CommonException("当前账户已禁用，请联系管理员！");
//            }
            // 记录最后一次登录时间
            user.setLastLoginTime(CommonDateUtil.nowDateTime());
            Boolean execute = transactionTemplate.execute(e -> {
                try {
                    userService.updateMember(user);
                } catch (ServiceException serviceException) {
                    serviceException.printStackTrace();
                }
                return Boolean.TRUE;
            });
            if (!execute) {
                logger.error(StrUtil.format("APP微信登录记录最后一次登录时间失败，uid={}", user.getId()));
            }


            System.out.print("111111111111");

            return getLoginResponseNew(user,false);
        }else {
//            // 没有用户，走创建用户流程
//            // 从微信获取用户信息，存入Redis中，将key返回给前端，前端在下一步绑定手机号的时候下发
            RegisterThirdUserRequest registerThirdUmsMemberRequest = new RegisterThirdUserRequest();
            registerThirdUmsMemberRequest.setSpreadPid(0);
            registerThirdUmsMemberRequest.setType(request.getType());
            registerThirdUmsMemberRequest.setOpenId(request.getOpenId());
            String key = SecureUtil.md5(request.getOpenId());
            redisUtil.set(key, JSONObject.toJSONString(registerThirdUmsMemberRequest), (long) (60 * 2), TimeUnit.MINUTES);
//            LoginResponse loginResponse = new LoginResponse();
//            loginResponse.setType(LoginConstants.LOGIN_STATUS_REGISTER);
//            loginResponse.setKey(key);
//            return loginResponse;


            UmsMember member = new UmsMember();
            member.setType(CommonConstant.BUYER);

            member.setRegisterType(registerThirdUmsMemberRequest.getType());
//            member.setPhone(registerThirdUmsMemberRequest.getPhone());
//            user.setAccount(request.getPhone());
//            user.setSpreadUid(0);
//            member.setPassword(passwordEncoder.encode(regParam.getPassword()));
            member.setPassword(CommonUtil.createPwd(com.chengyu.core.utils.StringUtils.getStringRandom(32)));
            member.setNickname(registerThirdUmsMemberRequest.getOpenId());
            member.setCode(registerThirdUmsMemberRequest.getOpenId());
            member.setHeadImg(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
            member.setGender("");
            member.setAddress("");
            member.setLastLoginTime(CommonDateUtil.nowDateTime());
            UmsMember finalUmsMember = member;

//            LoginResponse loginResponse = new LoginResponse();
//            loginResponse.setTokenHead(tokenHead);

//            tokenMap.put("member", member);

            System.out.print(finalUmsMember);
            try {
                Boolean execute = transactionTemplate.execute(e -> {
                    //进行注册登录
                    String token = "";
                    try {
                        userService.register(finalUmsMember, false);



//                        token  = userService.loginByNoPassword(finalUmsMember.getCode());
//                        loginResponse.setToken(token);
                    } catch (ServiceException serviceException) {
                        serviceException.printStackTrace();
                    }
                   //if (token == null) {return CommonResult.validateFailed("用户名或密码错误");}
                    return null;
                });

                System.out.print("22222222222");
                //校验code是否已被注册
                UmsMember user = userService.getMemberByParams(registerThirdUmsMemberRequest.getOpenId(), MemberTypes.CODE);


//                if (request.getType().equals(UserConstants.REGISTER_TYPE_IOS_WX)) {
                    userTokenService.bind(registerThirdUmsMemberRequest.getOpenId(), UserConstants.USER_TOKEN_TYPE_WECHAT, user.getId());
//                }
//                if (request.getType().equals(UserConstants.REGISTER_TYPE_ANDROID_WX)) {
//                    userTokenService.bind(registerThirdUmsMemberRequest.getOpenId(), UserConstants.USER_TOKEN_TYPE_ANDROID_WX, user.getId());
//                }
//                UmsMember user = userService.getMemberByParams(userToken.getUid());
                return getLoginResponseNew(user,true);

            } catch (TransactionException e) {
                e.printStackTrace();

                System.out.print("3333333333");
//                LoginResponse loginResponse = new LoginResponse();
                return  getLoginResponseNew(null,true);
            }
        }

    }


    /**
     * ios登录
     */
    @Override
    public LoginResponse ioslogin(IosLoginRequest loginRequest) {
        // 检测是否存在
        logger.info("ios ================ 登录 请求参数：loginRequest = " + loginRequest);
        UserToken userToken = userTokenService.getByOpenidAndType(loginRequest.getOpenId(), UserConstants.USER_TOKEN_TYPE_IOS);
        if (ObjectUtil.isNotNull(userToken)) {// 已存在，正常登录
            UmsMember user = userService.getById(userToken.getUid());
            if (ObjectUtil.isNull(user) && user.getStatus()!=1) {
                throw new CommonException("当前账户异常，请联系管理员！");
            }
//            if (!user.getStatus()) {
//                throw new CommonException("当前账户已禁用，请联系管理员！");
//            }
            // 记录最后一次登录时间
            user.setLastLoginTime(CommonDateUtil.nowDateTime());
            Boolean execute = transactionTemplate.execute(e -> {
                try {
                    userService.updateMember(user);
                } catch (ServiceException serviceException) {
                    serviceException.printStackTrace();
                }
                return Boolean.TRUE;
            });
            if (!execute) {
                logger.error(StrUtil.format("App记录用户最后一次登陆时间失败，uid={}", user.getId()));
            }
            return getLoginResponse(user);
        }
        // 没有用户Ios直接创建新用户
        UmsMember user = new UmsMember();
        String randomString = RandomUtil.randomString(11);
        user.setPhone("");
        user.setCode(randomString);
        user.setTjrUid(0);
//        user.setPassword("123");


        user.setPassword(CommonUtil.createPwd("1555555555"));
        user.setNickname(CommonUtil.createNickName("1555555555"));
        user.setHeadImg(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
        user.setGender("");
        user.setAddress("");


        user.setRegisterType(UserConstants.REGISTER_TYPE_IOS);
        user.setNickname(CommonUtil.createNickName(randomString));
//        user.setAvatar(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
//        user.setSex(0);
        user.setAddress("");
        user.setIsBindingIos(true);
        user.setLastLoginTime(CommonDateUtil.nowDateTime());
//        user.setLevel(1);
        Boolean execute = transactionTemplate.execute(e -> {
            try {
                userService.register(user, false);
            } catch (ServiceException serviceException) {
                serviceException.printStackTrace();
            }
//            userService.save(user);
            userTokenService.bind(loginRequest.getOpenId(), UserConstants.USER_TOKEN_TYPE_IOS, user.getId());
            return Boolean.TRUE;
        });
        if (!execute) {
            throw new CommonException("App用户注册生成失败，nickName = " + user.getNickname());
        }
        return getLoginResponse_V1_3(user, true);
    }

    /**
     * 校验token是否有效
     * @return true 有效， false 无效
     */
    @Override
    public Boolean tokenIsExist() {
//        Integer userId = userService.getUmsMemberId();
//        return userId > 0;
         return  false;
    }

    private LoginResponse commonLogin(UmsMember user, Integer spreadPid) throws ServiceException {
        if (user.getTjrUid().equals(0) && spreadPid > 0) {
            // 绑定推广关系
            bindSpread(user, spreadPid);
        }
        // 记录最后一次登录时间
        user.setLastLoginTime(CommonDateUtil.nowDateTime());
        userService.updateMember(user);
//        if (!b) {
            logger.error("用户登录时，记录最后一次登录时间出错,uid = " + user.getId());
//        }
        return getLoginResponse(user);
    }

    private LoginResponse getLoginResponse(UmsMember user) {
        //生成token
        LoginResponse loginResponse = new LoginResponse();
        String token = tokenComponent.createToken(user);
        loginResponse.setToken(token);
        loginResponse.setId(user.getId());
        loginResponse.setNikeName(user.getNickname());
        loginResponse.setPhone(CommonUtil.maskMobile(user.getPhone()));
        loginResponse.setType(LoginConstants.LOGIN_STATUS_LOGIN);
        loginResponse.setAvatar(user.getHeadImg());
        return loginResponse;
    }



    private LoginResponse getLoginResponseNew(UmsMember user, Boolean isNew) throws ServiceException {


        System.out.println(user);
        System.out.println(isNew);
        //生成token
        if(user==null){
             return new LoginResponse();
        }
        LoginResponse loginResponse = new LoginResponse();

        loginResponse.setId(user.getId());
        loginResponse.setNikeName(user.getNickname());
//        loginResponse.setCode(user.getCode());
        loginResponse.setPhone(CommonUtil.maskMobile(user.getPhone()));

        loginResponse.setAvatar(user.getHeadImg());

        loginResponse.setIsNew(isNew);

        loginResponse.setType(LoginConstants.LOGIN_STATUS_LOGIN);
        if(user.getPhone()==null || user.getPhone().equals("")){
            loginResponse.setType("bindphone");
        }


//        String token = tokenComponent.createToken(user);
//        loginResponse.setToken(token);
        String token  = userService.loginByNoPassword(user.getCode());
        loginResponse.setToken(token);


        loginResponse.setTokenHead(tokenHead);



        return loginResponse;
    }




    private LoginResponse getLoginResponse_V1_3(UmsMember user, Boolean isNew) {
        //生成token
        LoginResponse loginResponse = new LoginResponse();
        String token = tokenComponent.createToken(user);
        loginResponse.setToken(token);
        loginResponse.setId(user.getId());
        loginResponse.setNikeName(user.getNickname());
        loginResponse.setPhone(CommonUtil.maskMobile(user.getPhone()));
        loginResponse.setType(LoginConstants.LOGIN_STATUS_LOGIN);
        loginResponse.setAvatar(user.getHeadImg());
        if (isNew) {
            loginResponse.setIsNew(true);
//            List<Coupon> couponList = couponService.sendNewPeopleGift(user.getId());
//            if (CollUtil.isNotEmpty(couponList)) {
//                loginResponse.setNewPeopleCouponList(couponList);
//            }
        }
        return loginResponse;
    }
}
